<template>
	<!-- minorPkg/pages/userEdit/phoneEdit.wxml -->
	<view class="body">
		<form class="form" @submit="formSubmit">
			<view class="input-items">
				<view class="form-item">
					<input class="form-item-input" type="number" name="phone" placeholder="输入旧手机号码" maxlength="11"
						style="border-bottom: 1rpx #f4f4f4 solid" @input="getOldUserPhone" :value="oldPhone" />
				</view>
				<view class="form-item">
					<input class="form-item-input" type="number" name="phone" placeholder="输入新手机号码" maxlength="11"
						style="border-bottom: 1rpx #f4f4f4 solid" @input="getUserPhone" :value="phone" />
				</view>
				<view class="form-item">
					<input class="form-item-input" type="number" name="code" placeholder="请输入验证码" :value="code" />
					<button class="code-btn" :disabled="codeBtnDisabled" @tap.stop.prevent="getCode"
						size="mini">{{ codeTips }}</button>
				</view>
			</view>
			<captcha product="bind" v-if="loadCaptcha" :verify="verify" :gt="gt" :challenge="challenge"
				:offline="offline" @onReady="captchaReady" @onError="captchaError" @onSuccess="captchaSuccess"
				@onClose="captchaClose" :toReset="toReset" />
			<button class="form-btn" form-type="submit"
				:style="'background-color:' + platformConfig.baseColor">保存</button>
		</form>
	</view>
</template>

<script>
	// minorPkg/pages/userEdit/phoneEdit.js
	const app = getApp();

	const utils = require('./../../../utils/util.js');
	import {
	  http
	} from '@/utils/commonRequest.js'; // 局部引入
	export default {
		components: {},
		data() {
			return {
				platformConfig: app.globalData.platformConfig,
				detailMemberInfo: null,
				codeTips: '验证码',
				codeBtnDisabled: false,
				phone: null,
				code: null,
				oldPhone: null,
				verify: false,
				loadCaptcha: false,
				gt: '',
				challenge: '',
				offline: '',
				product: '',
				result: '',
				toReset: false
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.platformConfig = app.globalData.platformConfig
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			this.getDetailMemberInfo();
			this.captchaRegister();
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			/**
			 * 获取详细的会员信息
			 */
			getDetailMemberInfo: function() {
				let that = this;
				http.get('/personal/userInfo', {})
					.then((res) => {
						if ('200' == res.code) {
							console.log(res);
							let detailMemberInfoTmp = res.userinfo;
							that.detailMemberInfo = detailMemberInfoTmp
						}
					})
					.catch((err) => {
						utils.message('获取会员信息失败');
					});
			},

			/**
			 * 获取验证码
			 */
			getCode: function(e) {
				var phone = this.phone;
				var oldPhoneInput = this.oldPhone;

				if (utils.isEmpty(oldPhoneInput) || !utils.verifyPhone(oldPhoneInput)) {
					utils.message('请输入正确的原手机号！');
					return;
				}

				if (utils.isEmpty(phone) || !utils.verifyPhone(phone)) {
					utils.message('请输入正确的手机号！');
					return;
				}

				let oldPhone = this.oldPhone;

				if (!utils.isEmpty(oldPhone) && phone == oldPhone) {
					utils.message('新手机与旧手机号一致，请重新输入');
					return;
				}

				this.codeBtnDisabled = true
				var that = this;
				that.toVerify();
			},

			/**
			 * 监听用户输入的手机号
			 */
			getUserPhone: function(e) {
				let that = this;
				that.phone = e.detail.value
			},

			getOldUserPhone: function(e) {
				let that = this;
				that.oldPhone = e.detail.value
			},

			/**
			 * 修改手机号
			 */
			toSavePhone: function(phone, code, oldPhone) {
				var that = this;
				var params = {
					userPhone: phone,
					userCode: code,
					userOldPhone: oldPhone
				};
				http.post('member/savePhone', params,{header: {"content-type":"application/x-www-form-urlencoded"}})
					.then((res) => {
						uni.hideLoading();

						if ('200' == res.code) {
							if ('SUCCESS' == res.msg) {
								uni.showToast({
									title: '修改成功！'
								});
								setTimeout(function() {
									uni.navigateBack({});
								}, 2000);
							} else if ('WRONG' == res.msg) {
								utils.message('验证码或手机号不正确！');
							} else {
								utils.message(res.msg);
							}
						} else {
							utils.message('修改失败，请稍后再试！');
						}
					})
					.catch((err) => {
						uni.hideLoading();
						utils.message('修改失败，请稍后再试！');
					});
			},

			/**
			 * 表单提交
			 */
			formSubmit: function(e) {
				console.log(e);
				let oldPhone = this.oldPhone;

				if (!utils.isEmpty(oldPhone) && e.detail.value.phone == oldPhone) {
					utils.message('新手机与旧手机号一致，无法修改');
					return;
				}

				if (utils.isEmpty(e.detail.value.phone) || !utils.verifyPhone(e.detail.value.phone)) {
					utils.message('请输入正确的手机号！');
					return;
				}

				if (utils.isEmpty(oldPhone) || !utils.verifyPhone(oldPhone)) {
					utils.message('请输入正确的手机号！');
					return;
				}

				if (utils.isEmpty(e.detail.value.code)) {
					utils.message('验证码不能为空！');
					return;
				}

				uni.showLoading({
					title: '修改中,请稍后',
					mask: true
				});
				var that = this;
				this.$checkLogin().then((res) => {
					that.toSavePhone(e.detail.value.phone, e.detail.value.code, oldPhone);
				});
			},

			//极验初始化
			captchaRegister: function() {
				var that = this;
				var url = '/index/validateCodeGT?t=' + new Date().getTime();
				http.get(url, {}).then((res) => {
					that.loadCaptcha = true
					that.gt = res.gt
					that.challenge = res.challenge
					that.offline = !res.success
					that.product = 'float'
				});
			},

			captchaValidate: function() {
				console.log('app.globalData.JSESSIONID--->' + app.globalData.JSESSIONID);
				var that = this;
				var data = that.result;

				if (!data || (data && !data.geetest_challenge)) {
					console.log('请先完成验证！');
					return;
				}

				var url = 'index/sendCodeByGeetest';
				uni.showLoading({
					title: '发送中'
				});
				http.post(url, {
						geetest_challenge: data.geetest_challenge,
						geetest_validate: data.geetest_validate,
						geetest_seccode: data.geetest_seccode,
						phone: that.phone
					},{header: {"content-type":"application/x-www-form-urlencoded"}})
					.then((res) => {
						uni.hideLoading();

						if ('200' == res.code) {
							utils.message('验证码已发送');
							this.hasValidate = true;
							console.log('this.data.hasValidate--->' + this.hasValidate);
							let i = 60;
							let a = setInterval(function() {
								i--;

								if (i == 0) {
									that.codeTips = '验证码'
									that.codeBtnDisabled = false
									clearInterval(a);
								} else {
									that.codeTips = i + 'S'
								}
							}, 1000);
						} else {
							utils.message(res.msg);
							that.codeBtnDisabled = false
							that.btnReset();
						}
					})
					.catch((err) => {
						that.codeBtnDisabled = false
						this.btnReset();
					});
			},

			toVerify: function() {
				this.verify = true
			},

			captchaReady: function() {
				console.log('captcha-Ready!');
			},

			captchaError: function(e) {
				console.log('captcha-Error!', e
				.detail); // 这里对challenge9分钟过期的机制返回做一个监控，如果服务端返回code:21,tips:not proof，则重新调用api1重置

				if (e.detail.code === 21) {
					var that = this; // 需要先将插件销毁

					that.loadCaptcha = false

					that.captchaRegister();
				}
			},

			captchaSuccess: function(result) {
				console.log('captcha-Success!'); // 这里先将result中的参数保存，待进行二次验证时传入

				this.result = result.detail
				this.captchaValidate();
			},

			captchaClose: function() {
				console.log('captcha-Close!');
				this.codeBtnDisabled = false
			},

			btnReset: function() {
				// btnReset方法用户自定义
				// 如果采用现代框架，可能会因为diff导致设置失效，可以将true换成随机数 Date.now()
				this.toReset = true
			}
		}
	};
</script>
<style>
	.body {
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 100%;
	}

	.form {
		margin: 20rpx;
		width: 100%;
	}

	.form-item {
		height: 122rpx;
		font-size: 30rpx;
		position: relative;
	}

	.input-items {
		margin: 0 20rpx;
		display: flex;
		flex-direction: column;
		align-content: stretch;
		padding: 0 20rpx;
		background-color: white;
		border-radius: 10rpx;
	}

	.form-item-input {
		width: 100%;
		height: 120rpx;
		line-height: 120rpx;
		font-size: 30rpx;
		outline: none;
		color: #444;
	}

	button::after {
		border: none;
	}

	.form-btn {
		width: 95% !important;
		font-weight: normal;
		font-size: 36rpx;
		border-radius: 10rpx;
		color: white;
		margin: 40rpx 20rpx 0;
		letter-spacing: 4rpx;
	}

	.code-btn {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		display: inline-block;
		background-color: #fff;
		font-size: 30rpx !important;
		letter-spacing: 0.4rpx;
		color: #666;
		z-index: 999;
		font-weight: normal;
	}
</style>
